package doantotnghiep.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import doantotnghiep.business.CabinetBusiness;
import doantotnghiep.business.ImportedMedicamentBusiness;
import doantotnghiep.business.MedicamentBatchBusiness;
import doantotnghiep.business.MedicamentBusiness;
import doantotnghiep.business.StaffBusiness;
import doantotnghiep.model.Cabinet;
import doantotnghiep.model.ImportedDetail;
import doantotnghiep.model.ImportedMedicament;
import doantotnghiep.model.Medicament;
import doantotnghiep.model.MedicamentBatch;
import doantotnghiep.model.Staff;
import doantotnghiep.modelDTO.CabinetDTO;
import doantotnghiep.modelDTO.ImportedDetailDTO;
import doantotnghiep.modelDTO.ImportedMedicamentDTO;
import doantotnghiep.modelDTO.MedicamentBatchDTO;
import doantotnghiep.modelDTO.MedicamentDTO;
import doantotnghiep.modelDTO.StaffDTO;

@Controller
public class ImportedMedicamentController {

	@Autowired
	private StaffBusiness staffBusiness;
	@Autowired
	private MedicamentBusiness medicamentBusiness;
	@Autowired
	private ImportedMedicamentBusiness importedMedicamentBusiness;
	@Autowired
	private CabinetBusiness cabinetBusiness;
	@Autowired
	private MedicamentBatchBusiness batchBusiness;
	
	MedicamentBatchDTO[] batchDTOs;
	ImportedMedicament currentImported;

	private static ImportedDetailDTO[] importedDetailDTOs;
	private static MedicamentBatchDTO[] medicamentBatchDTOs;
	private static int countImportDetail = 0;
	private static int countBatchOfDetail = 0;

	@ModelAttribute("ImportedDetailDTO")
	public ImportedDetailDTO getImportedDetailDTOObject() {
		return new ImportedDetailDTO();
	}

	@ModelAttribute("ImportedMedicamentDTO")
	public ImportedMedicamentDTO getImportedMedicamentDTOObject() {
		return new ImportedMedicamentDTO();
	}

	@ModelAttribute("MedicamentBatchDTO")
	public MedicamentBatchDTO getMedicamentBatchDTOObject() {
		return new MedicamentBatchDTO();
	}

	// get request add a ImportedMedicament
	@RequestMapping(method = RequestMethod.GET, value = "/addImportedMedicament")
	public ModelAndView addImportMedicament() {

		importedDetailDTOs = new ImportedDetailDTO[20];
		for(int i = 0; i<importedDetailDTOs.length;i++){
			importedDetailDTOs[i] =  new ImportedDetailDTO();
		}

		List<Staff> staffs;
		List<StaffDTO> staffDTOs = new ArrayList<StaffDTO>();
		if (staffBusiness != null) {

			// get all Staff whose can create this importedmedicament
			staffs = staffBusiness.listImportValidStaff();
			if (staffs != null) {

				// transfer to DTO to view in jsp
				for (Staff staff : staffs) {
					StaffDTO staffDTO = new StaffDTO();
					staffDTO.setId(staff.getId());
					staffDTO.setFullName(staff.getFullName());

					staffDTOs.add(staffDTO);
				}
			}

			// set count detail variable to begin add detail
			countBatchOfDetail = 0;

			// put data into a map to return view
			Map<String, Object> staffModel = new HashMap<String, Object>();
			staffModel.put("staffDTOs", staffDTOs);
			return new ModelAndView("addImportedMedicament", "staffModel",
					staffModel);
		}
		return new ModelAndView("viewStaff", "", null);
	}

	/* receive require view all importedMedicament from client */
	@RequestMapping(value = "/viewImportedMedicament", method = RequestMethod.GET)
	public ModelAndView viewAllImportedMedicament() {
		List<ImportedMedicament> importedMedicaments;
		List<ImportedMedicamentDTO> importedMedicamentDTOs = new ArrayList<ImportedMedicamentDTO>();
		if (importedMedicamentBusiness != null) {

			// get a list of all medicament from database
			importedMedicaments = importedMedicamentBusiness
					.listImportedMedicament();
			if (importedMedicaments != null) {

				// transfering to MedicamentDTO
				for (ImportedMedicament me : importedMedicaments) {
					ImportedMedicamentDTO dto = new ImportedMedicamentDTO();
					dto.setId(me.getId());
					dto.setImportedDate(me.getImportedDate());
					dto.setStaffName(me.getStaff().getFullName());
					importedMedicamentDTOs.add(dto);
				}

				// put data into a Map Object to return to view
				Map<String, Object> importedModel = new HashMap<String, Object>();
				importedModel.put("importedMedicamentDTOs",
						importedMedicamentDTOs);

				return new ModelAndView("viewImportedMedicament",
						"importedModel", importedModel);
			}
		}
		return new ModelAndView("viewImportedMedicament", "", null);
	}
	/* receive require view all importedMedicament from client */
	@RequestMapping(value = "/searchImported", method = RequestMethod.GET)
	public ModelAndView searchImported(HttpServletRequest request, ModelMap model,
			String date) {
				List<ImportedMedicament> importedMedicaments;
				List<ImportedMedicamentDTO> importedMedicamentDTOs = new ArrayList<ImportedMedicamentDTO>();
				if (importedMedicamentBusiness != null) {

					// get a list of all medicament from database
					importedMedicaments = importedMedicamentBusiness
							.listImportedMedicamentByDate(date);
					if (importedMedicaments != null) {

						// transfering to MedicamentDTO
						for (ImportedMedicament me : importedMedicaments) {
							ImportedMedicamentDTO dto = new ImportedMedicamentDTO();
							dto.setId(me.getId());
							dto.setImportedDate(me.getImportedDate());
							dto.setStaffName(me.getStaff().getFullName());
							importedMedicamentDTOs.add(dto);
						}

						// put data into a Map Object to return to view
						Map<String, Object> importedModel = new HashMap<String, Object>();
						importedModel.put("importedMedicamentDTOs",
								importedMedicamentDTOs);

						return new ModelAndView("importedMedicamentSearchResult",
								"importedModel", importedModel);
					}
				}
				return new ModelAndView("viewImportedMedicament", "", null);
	}
	
	// receive request add detail for imported medicament
	@RequestMapping(value = "/addImportedDetail", method = RequestMethod.GET)
	public ModelAndView addDetail() {

		// put data into a map to return to view
		Map<String, Object> importedDetailModel = new HashMap<String, Object>();

		// put list detail to view to user
		importedDetailModel.put("importedDetailDTOs", importedDetailDTOs);

		return new ModelAndView("addImportDetail", "importedDetailModel",importedDetailModel);
	}

	@RequestMapping(value = "/addImportedDetailPost", method = RequestMethod.POST)
	public ModelAndView addDetail(
			HttpServletRequest request,ModelMap model,
			@ModelAttribute("ImportedDetailDTO") ImportedDetailDTO importedDetailDTO) {
		Map<String, Object> importedDetailModel = new HashMap<String, Object>();
		if (importedDetailDTO != null && importedDetailDTO.getNumberOfBatch() != 0) {

			// get name of medicament
			String medicamentName = medicamentBusiness.getMedicamentById(
					importedDetailDTO.getMedicamentID()).getMedicamentName();
			importedDetailDTO.setMedicamentName(medicamentName);
			int numberOfBatch = importedDetailDTO.getNumberOfBatch();
			float boughtPrice = medicamentBusiness.getMedicamentById(
					importedDetailDTO.getMedicamentID()).getBoughtPrice();
			importedDetailDTO.setImportCost((float) (numberOfBatch)* boughtPrice);

			// add detail to List at current position
			//importedDetailDTOs[countImportDetail].setBatchDTOs(importedDetailDTO.getBatchDTOs());
			System.out.println("chan countImportDetail= "+countImportDetail+"dia chi"+importedDetailDTOs[countImportDetail]);
			importedDetailDTOs[countImportDetail].setImportCost(importedDetailDTO.getImportCost());
			importedDetailDTOs[countImportDetail].setMedicamentID(importedDetailDTO.getMedicamentID());
			importedDetailDTOs[countImportDetail].setMedicamentName(importedDetailDTO.getMedicamentName());
			importedDetailDTOs[countImportDetail].setNumberOfBatch(importedDetailDTO.getNumberOfBatch());
	
			// increase count variable
			System.out.println("current number of detail: "+ countImportDetail);
	

			// get list all cabinet to contain batch of medicament
			List<Cabinet> cabinets = cabinetBusiness.listNotFullCabinet();
			ArrayList<CabinetDTO> cabinetDTOs = new ArrayList<CabinetDTO>();

			for (Cabinet c : cabinets) {
				CabinetDTO cabinetDTO = new CabinetDTO();
				cabinetDTO.setId(c.getId());
				cabinetDTO.setStatus(c.getStatus());
				cabinetDTO.setCabinetName(c.getCabinetName());
			
				cabinetDTOs.add(cabinetDTO);
			}

			countBatchOfDetail = 0;
			medicamentBatchDTOs = new MedicamentBatchDTO[importedDetailDTO.getNumberOfBatch()];//create new array to save batchs
			for(int i =0;i<medicamentBatchDTOs.length;i++){
				medicamentBatchDTOs[i] = new MedicamentBatchDTO();
			}
			System.out.println("tao xong mang có địa chỉ: "+medicamentBatchDTOs+"gom "+importedDetailDTO.getNumberOfBatch() +"phan tu de chua lo hang");

			// add data into a map to return for view
		
			importedDetailModel.put("cabinetDTOs", cabinetDTOs);
			importedDetailModel.put("importedDetailDTO", importedDetailDTO);
		
			return new ModelAndView("addBatchDetail", "importedDetailModel",
				importedDetailModel);
		}
		return new ModelAndView("addImportDetail", "importedDetailModel",
				importedDetailModel);
	}

	@RequestMapping(value = "/addBatchDetail", method = RequestMethod.POST)
	public synchronized String addBatchDetail(
			HttpServletRequest request,
			ModelMap model,
			@ModelAttribute("MedicamentBatchDTO") MedicamentBatchDTO medicamentBatchDTO) {
		
		if (medicamentBatchDTO != null) {
			System.out.println("NSX: "+medicamentBatchDTO.getDateOfManufacture());
			System.out.println("NHH: "+medicamentBatchDTO.getExpirationDate());
			System.out.println("TU: "+medicamentBatchDTO.getCabinet_ID());
			System.out.println("SH: "+medicamentBatchDTO.getBatchIdentifyNumber());
			medicamentBatchDTOs[countBatchOfDetail] = medicamentBatchDTO;
			return "redirect:/saveBatchDetail";			
		}
		return "addBatchDetail";
	}
	@RequestMapping(value = "/saveBatchDetail", method = RequestMethod.GET)
	public String saveBatchDetail() {
		System.out.println("importdetail " +countImportDetail+" co dia chi : "+importedDetailDTOs[countImportDetail]);
		importedDetailDTOs[countImportDetail].setBatchDTOs(medicamentBatchDTOs);
		countBatchOfDetail++;
		if(countBatchOfDetail == importedDetailDTOs[countImportDetail].getNumberOfBatch()){
			return "redirect:/saveImportedDetail";
		}
		else{
			return "addBatchDetail";
		}
	}

	@RequestMapping(value = "/saveImportedDetail", method = RequestMethod.GET)
	public String saveImportedDetail() {
		
		/*// get importeddetail element at last of list
		for(MedicamentBatchDTO i : medicamentBatchDTOs){
			System.out.println("lo truoc khi luu vao importdetail co dia chi la : "+i);
		}
		importedDetailDTOs[countImportDetail].setBatchDTOs(medicamentBatchDTOs);
		System.out.println("luu vao importdetail thi no co dc : "+importedDetailDTOs[countImportDetail].getBatchDTOs());
		for(MedicamentBatchDTO i : medicamentBatchDTOs){
			System.out.println("lo co dia chi la : "+i);
		}

		MedicamentBatchDTO[] batchDTOs = importedDetailDTOs[countImportDetail].getBatchDTOs();
		 for(int index = 0; index < batchDTOs.length ; index ++){
				if (batchDTOs[index] != null) {
						System.out.println("tam 1: "+batchDTOs[index].getBatchIdentifyNumber());
					}
		 }*/
		countBatchOfDetail = 0;//reset 
		countImportDetail++;//reset

		return "redirect:/addImportedDetail";
		}

	@RequestMapping(value = "/removeImportedDetail", method = RequestMethod.GET)
	public String removeImportedDetail() {

		// remove element
		importedDetailDTOs[countImportDetail] = null;

		// remove all batch which saved in list to preparing for insert new list
		// batch
		countImportDetail-- ;
		countBatchOfDetail = 0;
		
		return "redirect:/addImportedDetail";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/completeImported")
	public synchronized String addImportedMedicament(
			HttpServletRequest request,
			ModelMap model,
			@ModelAttribute("ImportedMedicamentDTO") ImportedMedicamentDTO importedDTO) {
		if (importedDTO != null && countImportDetail != 0) {

			// insert an importedmedicament
			ImportedMedicament importedMedicament = new ImportedMedicament();
			importedMedicament.setImportedDate(importedDTO.getImportedDate());

			//add staff
			Staff staff = new Staff();
			staff.setId(importedDTO.getStaff_ID());
			importedMedicament.setStaff(staff);
			
			//add imported id 
			importedMedicamentBusiness.addImportedMedicament(importedMedicament);
			System.out.println("finished insert phieu nhap");
			
			// get Max ID of table phieunhaphang(last inserted into phieunhaphang)
			currentImported = importedMedicamentBusiness.getInsertedImportedMedicament();
			System.out.println("ma phieu nhap vua chen la:"+currentImported.getId());
			
			/*begin add all imported detail from import*/
			int count = countImportDetail;
			System.out.println("so chi tiet can save la: "+count);
			for (int i = 0; i < count; i++) {
				System.out.println("bat dau them chi tiet thu: "+i);
				ImportedDetail importedDetail = new ImportedDetail();
				if (importedDetailDTOs[i] != null && importedDetailDTOs[i].getBatchDTOs() != null) {
					
					batchDTOs = importedDetailDTOs[i].getBatchDTOs();
					System.out.println("chi tiet nhap hop le");
					importedDetail.setNumberOfBatch(importedDetailDTOs[i].getNumberOfBatch());
					System.out.println("so lo sp tuong ung: "+importedDetail.getNumberOfBatch());
					
					// get a medicament and set it for detail
					Medicament medicament = new Medicament();
					medicament.setId(importedDetailDTOs[i].getMedicamentID());
					System.out.println("ma sp tuong ung: "+importedDetailDTOs[i].getMedicamentID());
					importedDetail.setMedicament(medicament);
					System.out.println("ma sp tuong ung sau khi set: "+importedDetail.getMedicament().getId());
				    
					//increase number of batch for this medicament
					medicamentBusiness.increaseNumberOfBatchofMedicine(importedDetailDTOs[i].getMedicamentID(),importedDetail.getNumberOfBatch());
					System.out.println("da tang so luong them "+importedDetail.getNumberOfBatch()+"cho sp tuong ung: "+importedDetail.getMedicament().getId());
					
					// set last inserted importedmediacament for detail and
					// insert
					// detail to table chitietnhaphang
					ImportedMedicament imported = new ImportedMedicament();
					imported.setId(currentImported.getId());
					
					importedDetail.setImportedMedicament(imported);
					importedDetail.setImportCost(importedDetailDTOs[i].getImportCost());
					//System.out.println("da set phieu nhap cho chi tiet: ");
					importedMedicamentBusiness.addDetailImported(importedDetail);
					
					System.out.println("add xong chi tiet nhap thu :"+i);
					System.out.println("\nchi tiet cac lo:");
										
					/*begin add all batch of each detail from import*/
					int index = 0;
					System.out.println("list batch size: " + batchDTOs.length);
					if (batchDTOs != null) {
						System.out.println("tesst: "+batchDTOs);
						for(MedicamentBatchDTO b: batchDTOs){
							System.out.println("dic chi cua batch : "+batchDTOs[index]);	
						}
					    for(index = 0; index < batchDTOs.length ; index ++){
							System.out.println("id cua batch thu : "+index+"la: "+batchDTOs[index]);	
					    	MedicamentBatchDTO b = batchDTOs[index];
								
					    		MedicamentBatch batch = new MedicamentBatch();

								batch.setAddedDate(importedDTO.getImportedDate());
								System.out.println("ngay nhp: "+batch.getAddedDate());
								batch.setDateOfManufacture(b.getDateOfManufacture());
								System.out.println("nsx:"+batch.getDateOfManufacture());
								batch.setExpirationDate(b.getExpirationDate());
								
								System.out.println("NHH: "+batch.getExpirationDate());
								batch.setBatchIdentifyNumber(b.getBatchIdentifyNumber());
								System.out.println("so hieu; "+batch.getBatchIdentifyNumber());
								
								// set cabinet for batch
								Cabinet cabinet = new Cabinet();
								cabinet.setId(batchDTOs[index].getCabinet_ID());
								batch.setCabinet(cabinet);
								
								System.out.println("add xong tu cho lo: " + batchDTOs.length);
								// set medicament for batch
								Medicament medicine = new Medicament();
								medicine.setId(importedDetailDTOs[i].getMedicamentID());
								batch.setMedicament(medicine);
								System.out.println("add xong san pham cho lo: " + batchDTOs.length);
								
								batchBusiness.addBatch(batch);
								System.out.println("add xong lo thu "+index);
							}
					}
				}else{
					System.out.println("chi tiet khong hop le nen ko save");
				}
			}
			
			//delete all data
			for (int i = 0; i < count; i++) {
				importedDetailDTOs[i] = null;
			}
			countBatchOfDetail = 0;
			countImportDetail = 0;
		}
		return "redirect:/viewImportedMedicament";
	}

	@RequestMapping(value = "/detailImported", method = RequestMethod.GET)
	public ModelAndView viewDetail(HttpServletRequest request, ModelMap model,
			int id) {
		List<ImportedDetail> importedDetails = importedMedicamentBusiness
				.getDetailByImportedID(id);
		List<ImportedDetailDTO> importedDetailDTOs = new ArrayList<ImportedDetailDTO>();

		// get all medicament to chooice when add a detail
		for (ImportedDetail m : importedDetails) {

			// transfer to DTO to view
			ImportedDetailDTO dto = new ImportedDetailDTO();
			dto.setNumberOfBatch(m.getNumberOfBatch());
			dto.setMedicamentName(m.getMedicament().getMedicamentName());
			dto.setMedicamentID(m.getMedicament().getId());
			int numberOfBatch = m.getNumberOfBatch();
			float boughtPrice = medicamentBusiness.getMedicamentById(
					m.getMedicament().getId()).getBoughtPrice();
			dto.setImportCost(numberOfBatch * boughtPrice);

			importedDetailDTOs.add(dto);
		}

		// put data into a map to return to view
		Map<String, Object> importedDetailModel = new HashMap<String, Object>();
		importedDetailModel.put("importedDetailDTOs", importedDetailDTOs);

		return new ModelAndView("viewImportDetail", "importedDetailModel",
				importedDetailModel);
	}
	
	@RequestMapping(value = "/findMedicineByName", method = RequestMethod.GET)
	public ModelAndView findMedicamentByName(HttpServletRequest request,
			ModelMap model, String key) {
		System.out.println("key:"+key);
		Map<String, Object> importedDetailModel = new HashMap<String, Object>();
		byte[] tmp = key.getBytes();
		String value="";
		try {
			value = new String(tmp,"UTF-8");
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println("value:"+value);
		ArrayList<MedicamentDTO> medicamentDTOs = new ArrayList<MedicamentDTO>();
	
		List<Medicament> medicaments = medicamentBusiness.getAllMedicamentByKeyWord(value);

		if (medicaments != null) {

			for (Medicament m : medicaments) {
				MedicamentDTO meDto = new MedicamentDTO();
				meDto.setId(m.getId());
				meDto.setMedicamentName(m.getMedicamentName());
				medicamentDTOs.add(meDto);
			}
			
			importedDetailModel.put("medicamentDTOs", medicamentDTOs);
																	
			importedDetailModel.put("importedDetailDTOs",importedDetailDTOs);// list detail entered
			
		}
		return new ModelAndView("addImportDetail", "importedDetailModel",
				importedDetailModel);
	}
}
